import React, { forwardRef, useState, useMemo } from 'react';
import { Col, Row, Select } from 'antd';
import { useSelector } from 'dva';
import { transformList } from '../utils';

const { Option } = Select;

const ChooseSub = forwardRef((props, ref) => {
  const { value, onChange } = props;
  const { innList = [], courierList = [] } = useSelector(({ order }) => order.exportOrderConfig);

  const { type: userType, ids } = value || {};

  const [type, setType] = useState(userType);

  const [id, setId] = useState(ids);

  const handleTypeChange = _type => {
    setType(_type);
    setId(['all']);
    onChange({
      ids: ['all'],
      type: _type,
    });
  };

  const handlePeopleChange = val => {
    const allIndex = val.findIndex(v => v == 'all');
    if (allIndex >= 0 && val.length > 1) {
      val.splice(allIndex, 1);
    } else if (val.length == 0) {
      val = ['all'];
    }
    setId(val);
    onChange({
      ids: val,
      type,
    });
  };

  const handlePeopleSelect = val => {
    if (val == 'all') {
      setId(['all']);
      onChange({
        ids: ['all'],
        type,
      });
    }
  };

  const list = useMemo(() => transformList(type, type == 'inn' ? innList : courierList), [
    innList,
    courierList,
    type,
  ]);

  const filterOption = (input, option) =>
    option.props.children && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;

  return (
    <Row type="flex" gutter={[10, 0]}>
      <Col span={5}>
        <Select ref={ref} placeholder="请选择下属类型" onChange={handleTypeChange} value={type}>
          <Option key="inn" value="inn">
            驿站
          </Option>
          <Option key="courier" value="courier">
            快递员
          </Option>
        </Select>
      </Col>
      <Col span={10}>
        <Select
          showSearch
          filterOption={filterOption}
          mode="multiple"
          placeholder="请选择具体驿站或快递员"
          onChange={handlePeopleChange}
          onSelect={handlePeopleSelect}
          value={id}
        >
          {list.map(val => (
            <Option value={val.id} key={val.id}>
              {val.name}
            </Option>
          ))}
        </Select>
      </Col>
    </Row>
  );
});

export default ChooseSub;
